﻿using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using Vote.Project001.Core.Infrastructure;

namespace Vote.Project001.Core.Framework
{
    public class Session
    {
        public Guid Id = Guid.NewGuid();
        public string Name { get; set; }
        public string UserId { get; set; }
        public bool Abandoned { get; set; }

        public DateTime LastUpdateTime = DateTime.Now;

        private Session(string name, string userId)
        {
            Name=name;
            UserId = userId;
            Abandoned = false;
        }

        internal static Session CreateSession(string code)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            var req = new OapiV2UserGetuserinfoRequest();
            req.Code = code;
            var rsp = client.Execute(req, SessionManager.Instance.AccessToken);

            if (rsp.Errcode != 0)
                throw new DingApiException($"v2/user/getuserinfo failed with code ({rsp.Errcode})\n{rsp.Errmsg}");

            var session = new Session(rsp.Result.Name, rsp.Result.Userid);

            return session;
        }
    }
}
